package HousingService.task2.serialization.db_exschange;

import HousingService.task2.serialization.serializator.JSNWriter;
import HousingService.task3.dao.HsAddressDao;
import HousingService.task3.dto.HsAddress;
import HousingService.task3.exceptions.HsAddressDaoException;
import HousingService.task3.factory.HsAddressDaoFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Linderhof
 * Date: 03.12.2010
 * Time: 13:48:09
 */
public class ImportDemo {
    private static final Logger logger =
            Logger.getRootLogger();

    public static void main(String[] args) {
        configureLogger();

        //Creating AddressDao
        HsAddressDao dao =
                HsAddressDaoFactory.create();

        //Deleting content of the table!!!
        deleteAll(dao);


        //Displaying content of DB table
        System.out.println("\nTable before import:\n");
        showAddressesFromDB(dao);


        //Specifying file to import
        File file = new JSNWriter().getAddressOut();

        //Actual import
        new Importer().importFile(dao, file);


        //Checking import results
        System.out.println("\nTable after import:\n");
        showAddressesFromDB(dao);

    }//main()

    private static void configureLogger() {
        final String logFilePath =
                ".\\timoshenko_housing\\src\\main\\logs\\ImportDemo.log";
        try {
            FileAppender appenderTXT =
                    new FileAppender(new SimpleLayout(), logFilePath);
            logger.addAppender(appenderTXT);
        } catch (IOException ioe) {
            System.out.println("Failed create log file");
        }
    }

    private static void deleteAll(HsAddressDao dao) {
        System.out.println("Starting deleting all from dao !!!");
        try {
            dao.deleteAllRecords();
            System.out.println("DAO successfully deleted!");
        } catch (HsAddressDaoException e) {
            e.printStackTrace();
        }
    }

    public static void showAddressesFromDB(HsAddressDao dao) {
        try {
            HsAddress[] result = dao.findAll();
            for (int i = 0; i < result.length; i++) {
                display(result[i]);
            }
        } catch (HsAddressDaoException e) {
            e.printStackTrace();
        }
    }//showAddressFromDB()

    public static void display(HsAddress dto)
	{
		StringBuffer buf = new StringBuffer();
		buf.append( dto.getAddressId() );
		buf.append( ", " );
		buf.append( dto.getStreet() );
		buf.append( ", " );
		buf.append( dto.getHouse() );
		buf.append( ", " );
		buf.append( dto.getFlat() );
		System.out.println( buf.toString() );
	}//display()

}//class ImportDemo
